﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;

using Entities;
using BLL;

namespace Stationery.UC
{
    public partial class UC_NewsAddUpdate : System.Web.UI.UserControl
    {
        #region Variables

        private BLL_News bll_News = new BLL_News();
        private BLL_NewsGroup bll_NewsGroup = new BLL_NewsGroup();
        private Entities.News obj_News = null;
        private Entities.User obj_User = null;
        private string vNews_id = "";

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            obj_User = (Entities.User)Session[Utils.SESSION_LOGIN];

            if (obj_User == null)
            {
                Response.Redirect(UtilsURL.home);
                return;
            }

            if (Request.Params["status"] != null)
            {
                string strStatus = Request.Params["status"].ToString();
                ViewState["STATUS"] = strStatus;
                LoadComboBoxNewsGroup();

                if (strStatus == "edit")
                {
                    vNews_id = Request.Params["newsid"].ToString();

                    if (vNews_id != null)
                    {
                        //Load Infor News
                        LoadNewsById(Convert.ToInt32(vNews_id));
                    }
                    else
                    {
                        //Redirect to news list
                        Response.Redirect(UtilsURL.news_list);
                    }
                }
            }
        }

        #endregion

        #region Load Data

        private void LoadComboBoxNewsGroup()
        {
            DataTable dt_newsGroup = null;
            dt_newsGroup = bll_NewsGroup.Get_All_NewsGroup();

            if (dt_newsGroup.Rows.Count <= 0)
            {
                ASPxComboBoxNewsGroup.SelectedIndex = -1;
            }
            else
            {
                ASPxComboBoxNewsGroup.DataSource = dt_newsGroup;
                ASPxComboBoxNewsGroup.TextField = "Group_name";
                ASPxComboBoxNewsGroup.ValueField = "Group_id";
                ASPxComboBoxNewsGroup.DataBind();
            }
        }

        private void LoadNewsById(int news_id)
        {
            string str_hotNews = "";
            DataTable dt = new DataTable();
            dt = bll_News.Get_News_ByID(news_id);

            if (dt == null)
            {
                //Khong lam gi
                return;
            }

            if (dt.Rows.Count <= 0)
            {
                Session["data"] = null;
                Response.Redirect(UtilsURL.news_list);
                return;
            }

            DataRow dtr = dt.Rows[0];
            ASPxComboBoxNewsGroup.Value = Convert.ToInt32(dtr["Group_id"].ToString());
            ASPxTextBoxTitle.Text = dtr["Title"].ToString();
            str_hotNews = dtr["IsHotNews"].ToString();

            if (str_hotNews == "Y")
            {
                ASPxCheckBoxHotNews.Checked = true;
            }
            else
            {
                ASPxCheckBoxHotNews.Checked = false;
            }
            if (dtr["Image_data"] != DBNull.Value)
            {
                byte[] blob = (byte[])dtr["Image_data"];
                ASPxBinaryImageData.ContentBytes = blob;
            }
            else
            {
                ASPxBinaryImageData.ContentBytes = null;
            }

            ASPxHtmlEditorNewsDesc.Html = dtr["Content_desc"].ToString();
            ASPxHtmlEditorNewsDetail.Html = dtr["Content_detail"].ToString();
        }

        private byte[] BmpToBytes(System.Drawing.Image bmp)
        {
            MemoryStream ms = null;
            byte[] bmpBytes = null;
            try
            {
                ms = new MemoryStream();
                // Save to memory using the Jpeg format
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                // read to end
                bmpBytes = ms.GetBuffer();
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                bmp.Dispose();
                if (ms != null)
                {
                    ms.Close();
                }
            }

            return bmpBytes;
        }

        #endregion

        #region Event Click
        protected void ASPxButtonAccept_Click(object sender, EventArgs e)
        {
            obj_News = new Entities.News();
            Int32 insert_id = 0;
            bool update = false;

            string imgContentType = "";

            if (Request.Params["status"] != null)
            {
                string strStatus = (string)ViewState["STATUS"];

                obj_News.TITLE = ASPxTextBoxTitle.Text.Trim();
                obj_News.CONTENT_DESC = ASPxHtmlEditorNewsDesc.Html.ToString();
                obj_News.CONTENT_DETAIL = ASPxHtmlEditorNewsDetail.Html.ToString();
                obj_News.GROUP_ID = Convert.ToInt32(ASPxComboBoxNewsGroup.Value);

                if (ASPxCheckBoxHotNews.Checked == true)
                {
                    obj_News.ISHOTNEWS = "Y";
                }
                else
                {
                    obj_News.ISHOTNEWS = "N";
                }

                if (strStatus == "edit")
                {
                    if (Request.Params["newsid"] != null)
                    {
                        int news_id      = Convert.ToInt32(Request.Params["newsid"].ToString());
                        obj_News.NEWS_ID = news_id;
                        obj_News.UPDATE_USER_ID = obj_User.ID; //User id Login  
                      
                        //Xu ly image
                        if (ASPxUploadControlImage.FileName == "")
                        {
                            //ko cap nhat Image                            
                            update = bll_News.UpdateNewsNotImage(obj_News);
                        }
                        else
                        {
                            imgContentType = ASPxUploadControlImage.PostedFile.ContentType;
                            if (imgContentType.ToLower().StartsWith("image"))
                            {
                                //get the image from upload stream
                                System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ASPxUploadControlImage.PostedFile.InputStream);
                                obj_News.IMAGE_DATA = BmpToBytes(b);

                                update = bll_News.UpdateNews(obj_News);
                            }
                            else
                            {
                                ASPxLabelException.Text = "Không là file Image";
                            }
                        }
                        //end Xu ly Image

                        if (update)
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('Thành công!');location.href='Admin.aspx?id=news'", UtilsURL.news_list), true);
                        else
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('KHÔNG Thành công!');location.href='Admin.aspx?id=news'", UtilsURL.news_list), true);
                    }
                }
                else if (strStatus == "add")
                {
                    ASPxBinaryImageData.Visible = true;
                    obj_News.USER_ID = obj_User.ID;//User_id Login
                    imgContentType = ASPxUploadControlImage.PostedFile.ContentType;

                    if (imgContentType.ToLower().StartsWith("image"))
                    {
                        //Get the image from upload stream
                        System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ASPxUploadControlImage.PostedFile.InputStream);
                        obj_News.IMAGE_DATA = BmpToBytes(b);
                    }
                    else
                    {
                        ASPxLabelException.Text = "Không là file Image";
                    }

                    insert_id = bll_News.InsertNews(obj_News);

                    if (insert_id > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('Thành công!');location.href='Admin.aspx?id=news&status=add'", UtilsURL.news_add), true);
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "message", String.Format("alert('KHÔNG Thành công!');location.href='Admin.aspx?id=news&status=add'", UtilsURL.news_add), true);
                    }
                }

                Session["data"] = null;
            }
        }

        protected void ASPxButtonCancel_Click(object sender, EventArgs e)
        {
            Session["data"] = null;
            Response.Redirect(UtilsURL.news_list);
        }
        #endregion
    }
}